import React, { FC, ReactElement, useCallback, useState, useEffect, useReducer } from 'react';
import { ITodo, IState, ACTION_TYPE } from './typings';

import TdList from './List';
import TdInput from './Input';

import { todoReducer } from './reducer';

// const initialState: IState = {
//   todoList: []
// }

// 惰性初始化
function init(initTodoList: ITodo[]): IState {
  return {
    todoList: initTodoList
  }
}

const TodoList: FC = (): ReactElement => {

  // const [todoList, setTodoList] = useState<ITodo[]>([])
  // useReducer 更高级的useState 返回dispatch
  // const [state, dispatch] = useReducer(todoReducer, initialState)
  const [state, dispatch] = useReducer(todoReducer, [], init);
  const { todoList } = state;

  const addTodo = useCallback((todo: ITodo): void => {
    // setTodoList(todoList => [...todoList, todo]);
    dispatch({
      type: ACTION_TYPE.ADD_TODO,
      payload: todo
    })
  }, [])

  useEffect(() => {
    const todoList = JSON.parse(localStorage.getItem('todolist') || '[]');
    dispatch({
      type: ACTION_TYPE.INIT_TODOLIST,
      payload: todoList
    }) 
    console.log(todoList);
  }, []) // 这里没有依赖
  
  useEffect(() => {
    localStorage.setItem('todolist', JSON.stringify(state.todoList));
  }, [state.todoList])

  const removeTodo = useCallback(
    (id: number): void => {
      dispatch({
        type: ACTION_TYPE.REMOVE_TODO,
        payload: id
      })
    },
    [],
  )

  const toggleTodo = useCallback(
    (id: number): void => {
      dispatch({
        type: ACTION_TYPE.TOGGLE_TODO,
        payload: id
      })
    },
    [],
  )

  return (
    <div>
      <TdList 
        addTodo={ addTodo }
        todoList={ todoList }
      />
      <TdInput 
       todoList={ todoList }
       removeTodo={ removeTodo }
       toggleTodo={ toggleTodo }
      />
    </div>
  )
}

export default TodoList;
